package cn.forkway.learn.jdbcTry;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @program: java-learn-jdbc
 * @className: demo03.java
 * @author: River Ray
 * @description: prepareStatement实现
 * @createTime 2021年10月08日 16:58:00
 */
public class demo03 {
    public static void main(String[] args) {
        String out = "";
        while(!out.equals("success")) {
            Map<String, String> userLoginInfo = initUI();
            boolean success = login(userLoginInfo);
            out = success? "success":"fail";
           System.out.println(out);
        }

    }

   private static boolean login(Map<String, String> userLoginInfo) {
       boolean loginSucces = false;
      Connection conn = null;
      PreparedStatement ps = null;
      ResultSet rs = null;

      try {
         Class.forName("com.mysql.cj.jdbc.Driver");
         String URL = "jdbc:mysql://localhost:3306/jdbctest?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
         String USER = "root";
         String PWD = "250032";
         conn = DriverManager.getConnection(URL, USER, PWD);
         String sql = "select * from t_user where loginName=? and loginPwd =?";
         ps = conn.prepareStatement(sql);
         ps.setString(1,userLoginInfo.get("LoginName"));
         ps.setString(2,userLoginInfo.get("pwd"));
         rs = ps.executeQuery();
         if (rs.next()) {
            loginSucces = true;
         }
      } catch (ClassNotFoundException | SQLException e) {
         e.printStackTrace();
      } finally {
         if (rs != null) {
            try {
               rs.close();
            } catch (SQLException throwables) {
               throwables.printStackTrace();
            }
         }
         if (ps != null) {
            try {
               ps.close();
            } catch (SQLException throwables) {
               throwables.printStackTrace();
            }
         }
         if (conn != null) {
            try {
               conn.close();
            } catch (SQLException throwables) {
               throwables.printStackTrace();
            }
         }
      }
      return  loginSucces ;
   };

   private static Map<String, String> initUI() {
      Scanner s = new Scanner(System.in);
      System.out.print("userName-->");
      String loginName = s.nextLine();
      System.out.print("pwd-->");
      String pwd = s.nextLine();
//      SQL注入  还有效果吗 ？？？
//      sdasdsa' or "1"='1 再也没有效果了
      Map<String, String> userLoginInfo;
      userLoginInfo = new HashMap<>();
      userLoginInfo.put("LoginName", loginName);
      userLoginInfo.put("pwd", pwd);
      return userLoginInfo;
    };
}
